/**
 * Created by wzq on 14-9-5.
 */
/*
 // 本地存储字段
 lastCheckin: 'lastCheckin',// 上次是否checkin 通讯成功
 checkInCode: 'checkInCode',// 上次checkin的结果 // 2005不可用 2004可用
 auth_email: 'auth_email',// email
 auth_pwd: 'auth_pwd',// password
 regCode: 'regCode'// 授权结果 2001/2002/2003
 set_ip: true / false
 */

;
var accessAuth = (function() {
    var isDebug = false;
    var localIp = "http://172.16.1.43:8080";

    //
    var urlCheckin = "{ip}/mdm/api/v1/devices/{deviceId}/detail";
    var urlAuth = "{ip}/mdm/api/v1/devices/{deviceId}";
    var urlGetstatus = "{ip}/mdm/api/v1/approvals/{deviceId}";
    var deviceId;
    var deviceDetail;

    // 错误 报错
    var errCodeAndMsg = {
        "2001": "正在审批",
        "2003": "不能通过认证,请更换用户",
        "2005": "设备暂不可用,请稍候重试",
        "4004": "用户信息错误,请重新填写",
        "5000": "服务器错误,请稍候再试"
    };

    var errMsg_noDeviceId = "无法获取设备信息, 请确认app获取方式是否正确, 详情 http://bsl.foreveross.com/mdm-deploy/";

    var errMsg_undef = "未知状态";
    var errMsg_notReg = "请进行认证";
    var errMsg_network = "网络错误,请稍候再试";

    var succCallback; // 成功回调
    var failCallback; // 失败回调
    var shouldCheckin;

    /**
     * 初始化
     * @param afterInit 初始化后,回调函数
     */
    function initVar(afterInit) {
        // 初始化之后，执行回调
        function doAfterAllInit() {
            console.log('----init done---');
            afterInit();
        }

        // 检测是否已经初始化过
        if (deviceDetail) {
            doAfterAllInit();
            return;
        }

        // 获取deviceId
        function getDeviceId(afterGetDeviceId) {
            cordova.exec(function(result) {
                deviceId = result;
                if (!deviceId || deviceId === 'null') { //TODO
                    failCallback(errMsg_noDeviceId);
                    localStorage.err_noDeviceId = true;
                    return;
                }
                localStorage.err_noDeviceId = false;
                afterGetDeviceId();
            }, function(err) {
                console.log("getDeviceId err = " + err);
            }, "DeviceInfo", "getDeviceId", []);
        }

        //获取 device detail
        function getDeviceDetail(afterGetDeviceDetail) {
            cordova.exec(function(result) {
                deviceDetail = result;
                afterGetDeviceDetail();
            }, function(err) {
                console.log("getDeviceDetail err = " + err);
            }, "DeviceInfo", "getDeviceDetail", []);
        }

        // 获取ip
        function getIp(afterIp) {
            cordova.exec(function(ip) {
                console.log("ip=" + ip);
                initUrl(ip);
                afterIp();
            }, function(err) {
                console.log("getDeviceId err = " + err);
            }, "DeviceInfo", "getIp", []);
        }

        function initUrl(ip) {
            if (isDebug) {
                ip = localIp;
            }
            //
            urlAuth = urlAuth.replace('{ip}', ip);
            urlAuth = urlAuth.replace('{deviceId}', deviceId);
            //
            urlCheckin = urlCheckin.replace('{ip}', ip);
            urlCheckin = urlCheckin.replace('{deviceId}', deviceId);
            //
            urlGetstatus = urlGetstatus.replace('{ip}', ip);
            urlGetstatus = urlGetstatus.replace('{deviceId}', deviceId);
            //
            console.log('----------check all url-s------------');
            console.log('deviceId=' + deviceId);
            console.log('deviceDetail=' + deviceDetail);
            console.log('ip=' + ip);

            console.log('urlCheckin=' + urlCheckin);
            console.log('urlAuth=' + urlAuth);
            console.log('urlGetstatus=' + urlGetstatus);
        }

        getDeviceId(function() {
            getDeviceDetail(function() {
                getIp(function() {
                    doAfterAllInit();
                });
            });
        });
    }

    /**
     * 入口函数
     * @param regInfo 认证上传信息
     * @param succ 成功回调
     * @param fail 失败回调
     * @param needCheckIn 是否需要checkIn
     */
    function regAndCheckin(regInfo, succ, fail, needCheckIn) {
        console.log('\n\n------------------------------------------------------');
        succCallback = succ;
        failCallback = fail;
        shouldCheckin = needCheckIn;
        if (!localStorage.lastCheckin || localStorage.lastCheckin === "fail") {
            shouldCheckin = true;
        }
        // 初始化后，
        // 进行register(如果必要)->getStatus(如果必要)->checkIn(如果必要)->返回结果，执行回调succ/fail
        initVar(function() {
            // TODO 1 检测是否需要 register
            if (!localStorage.regCode) {
                console.log('--------null localStorage.regCode----------');
                if (regInfo && regInfo.email && regInfo.password) {
                    localStorage.auth_email = regInfo.email;
                    localStorage.auth_pwd = regInfo.password;
                    register(regInfo, checkIn);
                } else {
                    checkIn();
                }
            }
            //
            else if (localStorage.regCode === "2001" || localStorage.regCode === "2003") {
                console.log('localStorage.regCode =' + localStorage.regCode);
                getStatus(checkIn);
            } else if (localStorage.regCode === "4004" && regInfo) {
                // 4004 => re-register
                register(regInfo, checkIn);
            } else if (localStorage.regCode === "5000" && regInfo) {
                // 4004 => re-register
                register(regInfo, checkIn);
            } else {
                console.log('localStorage.regCode =' + localStorage.regCode);
                checkIn();
            }
        });
    }

    /**
     * 去checkin
     */
    function checkIn() {
        console.log("---------test checkin condition-----------");
        console.log("shouldCheckin =" + shouldCheckin);
        console.log("localStorage.lastCheckin =" + localStorage.lastCheckin);

        if (shouldCheckin || !(localStorage.lastCheckin === "succ")) {
            console.log("-----------checkIn-----------");

            function httpSucc(result) {
                localStorage.lastCheckin = "succ";
                console.log("checkIn result=" + ((typeof result === 'string') ? result : JSON.stringify(result)) + "\n------------");
                var status = parseResult(result);
                localStorage.checkInCode = status.detail.code;
                checkAllResult();
            }

            function httpErr(xhr, type) {
                failCallback(errMsg_network);
                localStorage.lastCheckin = "fail";
            }

            makeAjaxRequest(urlCheckin, deviceDetail, 'POST', httpSucc, httpErr);
        } else {
            checkAllResult();
        }
    }

    /**
     * 获取状态 get status
     */
    function getStatus(callback) {
        console.log("--------------getStatus-----------------");

        function httpSucc(result) {
            console.log("getStatus result=" + ((typeof result === 'string') ? result : JSON.stringify(result)) + "\n------------");
            var status = parseResult(result);
            localStorage.regCode = status.detail.code;
            callback();
        }

        function httpErr(xhr, type) {
            failCallback(errMsg_network);
        }

        makeAjaxRequest(urlGetstatus, null, 'GET', httpSucc, httpErr);
    }

    /**
     * 结果返回
     */
    function checkAllResult() {
        // 检测本地存储 访问控制授权 registerStatus
        if (!localStorage.regCode) {
            console.log("首次授权");
            failCallback(errMsg_notReg);
        }

        // 已经 发起过认证
        else {
            var regCode = localStorage.regCode;
            console.log("regCode = " + regCode);
            if ("2002" === regCode) {
                if (localStorage.lastCheckin === "succ") {
                    if (localStorage.checkInCode === "2004") {
                        succCallback();
                        return;
                    }

                    var checkinErrMsg = errCodeAndMsg[localStorage.checkInCode];
                    if (!checkinErrMsg) {
                        checkinErrMsg = errMsg_network;
                    }
                    failCallback(checkinErrMsg);
                } else {
                    failCallback(errMsg_network);
                }
            } else {
                var errMsg = errCodeAndMsg[regCode];
                console.log("errMsg = " + errMsg);
                if (!errMsg) {
                    errMsg = errMsg_undef;
                }
                failCallback(errMsg);
            }
        }
    }

    /**
     * 认证，然后执行callback
     * @param regInfo
     * @param callback
     */
    function register(regInfo, callback) {
        console.log("--------------register--------------");
        //        var json = {};
        //        json.email = email;
        //        json.password = pwd;

        console.log("---上送数据" + JSON.stringify(regInfo));

        function httpSucc(result) {
            console.log("register result=" + ((typeof result === 'string') ? result : JSON.stringify(result)) + "\n------------");
            var status = parseResult(result);
            localStorage.regCode = status.detail.code;
            callback();
        }

        function httpErr(xhr, type) {
            failCallback(errMsg_network);
            callback();
        }

        makeAjaxRequest(urlAuth, JSON.stringify(regInfo), 'PUT', httpSucc, httpErr);
    }

    /**
     *
     * @param theUrl
     * @param data 注意为string 对象,通常是 JSON.stringify(json)
     * @param method
     * @param succ
     * @param error
     */
    function makeAjaxRequest(theUrl, data, method, succ, error) {
        console.log("------------ajax---------------");
        console.log("url=" + theUrl);
        console.log("data=" + data);
        $.ajax({
            type: method,
            url: theUrl,
            data: data,
            contentType: "application/json; charset=utf-8",
            timeout: 10000,
            success: succ,
            error: error
        });
    }

    /**
     * 解析接口返回的结果
     * @param str
     * @returns json对象
     */
    function parseResult(str) {
        var json = str;
        if (typeof str === 'string') {
            json = JSON.parse(str);
        }

        var detailStr = json.detail;
        json.detail = JSON.parse(detailStr);
        console.log("detail.code=" + json.detail.code);
        console.log("detail.desc=" + json.detail.desc);
        return json;
    }

    /**
     * 返回出错的提示信息
     * @returns {*}
     */
    function getErrMsg() {
        var errMsg;
        if (localStorage.regCode) {
            errMsg = errCodeAndMsg[localStorage.regCode];
            if (!errMsg) {
                if (localStorage.regCode === "2002") {
                    if (localStorage.checkInCode === "2005") {
                        errMsg = errCodeAndMsg["2005"];
                    } else {
                        errMsg = errMsg_network;
                    }
                } else {
                    errMsg = errMsg_undef;
                }
            }
        } else if (localStorage.err_noDeviceId === true) {
            errMsg = errMsg_noDeviceId;
        } else {
            errMsg = errMsg_notReg;
        }

        return errMsg;
    }

    function allOk() {
        console.log('--all ok--');
        window.location.replace("../exhibition/index.html");
    }

    function requireLogin() {
        console.log('--requireLogin--');
        window.location.replace("./register.html");
    }

    function logout() {
        localStorage.removeItem('regCode');
        localStorage.removeItem('lastCheckin');
        localStorage.removeItem('checkinCode');
        localStorage.removeItem('auth_email');
        localStorage.removeItem('auth_pwd');
    }

    function getAuthEmail() {
        return localStorage.auth_email ? localStorage.auth_email : '';
    }

    function getAuthPwd() {
        return localStorage.auth_pwd ? localStorage.auth_pwd : '';
    }

    function getMdmHost(callback) {
        cordova.exec(function(ip) {
            callback(null, ip)
        }, function(err) {
            callback(err)
        }, "DeviceInfo", "getIp", []);
    }

    function setMdmHost(host, callback) {
        cordova.exec(function() {
            localStorage.setIp = true;
            callback();
        }, function(err) {
            callback(err);
        }, "DeviceInfo", "setIp", [host]);
    }

    function isIpSetted() {
        console.log('localStorage.setIp=' + localStorage.setIp);
        if (localStorage.setIp) {
            return true;
        }
        return false;
    }

    return {
        regAndCheckin: regAndCheckin,
        getErrMsg: getErrMsg,
        allOk: allOk,
        requireLogin: requireLogin,
        logout: logout,
        getAuthEmail: getAuthEmail,
        getAuthPwd: getAuthPwd,
        isDebug: isDebug,
        getMdmHost: getMdmHost,
        setMdmHost: setMdmHost,
        isIpSetted: isIpSetted
    }
})();